<template>
	<sw-common-frame>
		<div slot="header" class="member_operate">
			<el-checkbox :indeterminate="isIndeterminate" :disabled="allDisabled" v-model="allChecked" @change="handleCheckboxAllChecked">
				{{ checkedMember.length > 0 ? `已选 ${checkedMember.length} 项` : '全选' }}
			</el-checkbox>
			<el-button-group v-if="checkedMember.length > 0">
				<el-button type="text" icon="el-icon-delete" @click="handleDeleteMemeber()">批量删除</el-button>
				<el-button type="text" icon="el-icon-sort" @click="handleMoveMember()">批量移动</el-button>
			</el-button-group>
		</div>
		<el-scrollbar class="member_scrollbar" slot="component">
			<el-checkbox-group class="member_listbox" v-model="checkedMember" :disabled="disabled" @change="handleCheckboxChecked" aria-hidden>
				<el-checkbox v-for="(item, index) in memberTableData" :key="index" :label="item.id" :disabled="item.pcId === userId">
					<template v-if="item.pcId === userId">
						<i class="el-icon-badge-manage" v-if="item.pcId === userId"></i>
					</template>
					<el-button class="delete" icon="el-icon-delete" @click="handleDeleteMemeber(item)"></el-button>
					<el-avatar :size="64" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
					<h4>{{ item.pcName || '无用户' }}</h4>
				</el-checkbox>
				<div v-if="!disabled" class="add-member" @click="handleAddedMember()">
					<i class="el-icon-plus"></i>
					<h4>添加成员</h4>
				</div>
			</el-checkbox-group>
			<div class="member_loadmore" v-if="$slots.more">
				<slot name="more"></slot>
			</div>
		</el-scrollbar>
		<select-user v-model="userDialog" :role-id="roleId" :library-id="libraryId" @refresh="updateLibraryMember"></select-user>
	</sw-common-frame>
</template>

<script>
import { move } from 'lodash';
import selectUser from './user';
import { mapGetters } from 'vuex';
import moveSelect from './moveSelect';
import { batchDelLibMember, batchMoveLibMember } from '@/api/data/tbNetPower';
export default {
	components: { selectUser },
	props: {
		count: { type: Number, default: 0 },
		roleId: { type: String, default: '' },
		list: { type: Array, default: () => [] },
		libraryId: { type: String, default: '' },
		disabled: { type: Boolean, default: false }
	},
	data() {
		return {
			checkedRole: '',
			allChecked: false,
			userDialog: false,
			checkedMember: [],
			memberTableData: [],
			isIndeterminate: false
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		userId() {
			return this.userInfo.id;
		},
		dataCount() {
			let isExist = this.memberTableData.some((n) => n.pcId !== this.userId);
			return isExist ? this.count - 1 : this.count;
		},
		checkedDatas() {
			let arr = this.memberTableData;
			return this.checkedMember.map((item) => {
				return arr.find((n) => n.id === item);
			});
		},
		allDisabled() {
			let dataArr = this.memberTableData.filter((n) => n.pcId !== this.userId);
			return this.disabled || dataArr.length === 0;
		}
	},
	watch: {
		roleId() {
			this.isIndeterminate = false;
			this.memberTableData = [];
			this.checkedMember = [];
			this.allChecked = false;
		},
		list(arr) {
			let dataArr = [...this.memberTableData, ...arr];
			if (dataArr.some((n) => n.pcId === this.userId)) {
				let index = dataArr.findIndex((n) => n.pcId === this.userId);
				let arrItem = dataArr.splice(index, 1)[0];
				this.memberTableData = [arrItem, ...dataArr];
			} else {
				this.memberTableData = [...dataArr];
			}
		}
	},
	methods: {
		//全选操作
		handleCheckboxAllChecked(flag) {
			let selectables = this.memberTableData.filter((n) => n.pcId !== this.userId);
			this.checkedMember = !flag ? [] : selectables.map((n) => n.id);
			this.isIndeterminate = flag && selectables.length !== this.dataCount;
		},

		//选择操作
		handleCheckboxChecked(arr) {
			let count = arr.length;
			this.allChecked = count === this.dataCount;
			this.isIndeterminate = count > 0 && count < this.dataCount;
		},

		//添加成员操作
		handleAddedMember() {
			this.userDialog = true;
		},

		//删除用户操作
		handleDeleteMemeber(data) {
			let that = this;
			let checkedArr = !data ? this.checkedDatas.map((n) => n.pcName) : [data.pcName];
			let deleteTexts = checkedArr.map((item) => `【${item}】`).join('');
			that.$confirm(`此操作将永久删除库成员<font color="#f00">${deleteTexts}</font>, 是否继续?`, '删除提示', {
				type: 'warning',
				dangerouslyUseHTMLString: true,
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await that.deleteLibMemberRequest(data);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//删除库成员请求
		async deleteLibMemberRequest(data) {
			let params = { id: !data ? this.checkedMember.join() : data.id };
			let result = await batchDelLibMember(params).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('删除库成员成功');
				this.updateLibraryMember();
			}
		},

		//库成员移动角色
		async handleMoveMember(data) {
			let that = this;
			let checkedRole = '';
			let createEle = that.$createElement;
			that.$handleMsgBoxEvent({
				title: '库成员移动到',
				message: createEle(moveSelect, {
					domProps: { value: checkedRole },
					props: { libraryId: that.libraryId, roleId: that.roleId },
					on: { input: (e) => (checkedRole = e) }
				}),
				async confirm() {
					let params = { id: that.checkedMember.join(), roleId: checkedRole };
					let result = await batchMoveLibMember(params).then((res) => res.data);
					if (result.code === '0') {
						that.$message.success('移动库成员成功');
						that.updateLibraryMember();
					}
					checkedRole = '';
				}
			});
		},

		//更新库角色成员
		updateLibraryMember() {
			this.isIndeterminate = false;
			this.memberTableData = [];
			this.checkedMember = [];
			this.allChecked = false;
			this.$emit('refresh');
		}
	}
};
</script>

<style lang="scss" scoped>
@import './member.scss';
</style>
